package cn.aezo.minions.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.LinkedHashMap;

@Component
public class WxAuthService {
    private Logger logger = LoggerFactory.getLogger(WxAuthService.class);

    @Autowired
    private RestTemplate restTemplate;

    //请求此地址即跳转到二维码登录界面
    private static final String AuthorizationUrl =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";

    // 获取用户 openid 和 access_token 的 URL
    private static final String AccesstokeOpenidUrl =
            "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    private static final String RefreshTokenUrl =
            "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=%s&grant_type=refresh_token&refresh_token=%s";

    private static final String UserInfoUrl =
            "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    private static final String Scope = "snsapi_userinfo";

    @Value("${help.wxAppId}")
    private String wxAppId;

    @Value("${help.wxAppSecret}")
    private String wxAppSecret;

    @Value("${help.wxCallbackUrl}")
    private String wxCallbackUrl;

    public String getAuthorizationUrl() throws UnsupportedEncodingException {
        wxCallbackUrl = URLEncoder.encode(wxCallbackUrl, "utf-8");
        String url = String.format(AuthorizationUrl, wxAppId, wxCallbackUrl, Scope, System.currentTimeMillis());
        return url;
    }

    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb50d02d2fd72d2d2&redirect_uri=http%3a%2f%2fxy9h4b.natappfree.cc/page/Index.html&response_type=code&scope=snsapi_userinfo&state=gzh#wechat_redirect
    // https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb50d02d2fd72d2d2&secret=60a34a5c4159d5092b9e557ac2aa63b9&code=0819ZELf1wqDLx0iy3If13gBLf19ZEL7&grant_type=authorization_code
    // {access_token=1X3GsW3imLHaFOjAvu701pASllYNG2Tl-PyzPSqfidjvCZnWdYNIPDXvvKbzeKK_6ibhtjvKMOF2ZzXJ_3uQDQ, expires_in=7200, refresh_token=iGHHuwvFnmTIJ9HmqPyPaGjTDSRYWloFkS7rn5WB6nDm3g4wAtz27eFtN-B1ajBEdKWp3g3woEYhZOmqL3lV8g, openid=oL2F31vtHbKxZxWEY0f-yOI7lIdE, scope=snsapi_userinfo}
    // userInfoStr = {openid=oL2F31vtHbKxZxWEY0f-yOI7lIdE, nickname=月星墙, sex=1, language=zh_CN, city=武汉, province=湖北, country=中国, headimgurl=http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83erKS3ICAPZFkFyLkhfcD6Ftb0bKmG0nNE9Eusg2IXyLXrwyZID2cS9mT7TS28ecTxNh02ZouXvC8w/0, privilege=[]}
    public LinkedHashMap getUserAccessTokenAndOpenid(String code) {
        String url = String.format(AccesstokeOpenidUrl, wxAppId, wxAppSecret, code);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        LinkedHashMap resp = restTemplate.getForObject(uri, LinkedHashMap.class);
        logger.info("getUserAccessTokenAndOpenid resp = " + resp);

        if(resp.containsKey("errcode")) {
            throw new RuntimeException("获取token错误信息，msg = " + resp);
        } else {
            return resp;
        }
    }

    public String getOpenId(String accessToken) {
        return null;
    }

    public LinkedHashMap getUserInfo(String accessToken, String openId){
        String url = String.format(UserInfoUrl, accessToken, openId);
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        LinkedHashMap resp = restTemplate.getForObject(uri, LinkedHashMap.class);
        logger.info("getUserInfo resp = " + resp);

        if(resp.containsKey("errcode")) {
            throw new RuntimeException("获取用户信息错误，msg = "+resp);
        } else {
            return resp;
        }
    }

    public LinkedHashMap getUserAccessTokenByRefreshToken(String refreshToken) {

        String url = String.format(RefreshTokenUrl, wxAppId, refreshToken);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        URI uri = builder.build().encode().toUri();

        LinkedHashMap resp = restTemplate.getForObject(uri, LinkedHashMap.class);
        logger.info("getUserAccessTokenByRefreshToken resp = " + resp);

        if(resp.containsKey("errcode")) {
            throw new RuntimeException("重新获取AccessToken失败，msg = "+resp);
        } else {
            return resp;
        }
    }
}
